﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Nate_sRoguelikeGame
{
    class MapBlock
    {
        public Point RelativeLocation;
        public Point DrawingOffset = new Point(0, 0);
        public Point Location;
        private List<GameObject> _contents = new List<GameObject>();
        private GameObject TopObject;
        public Level Level { get; set; }
        public bool IsOccupied { get { return _contents.Any(c => c is GameCharacter); } }
        
        private GameArchitecture _architecture;

        public MapBlock(Level level, Point location)
        {
            Level = level;
            Location = location;
        }

        public GameArchitecture Architecture
        {
            get { return _architecture; }
            set { _architecture = value;
                ResetTopObject();
            }
        }

        public void AddObject(GameObject gObject)
        {
            _contents.Add(gObject);
            ResetTopObject();
        }

        public void Draw()
        {
            Console.SetCursorPosition(Location.X + DrawingOffset.X + Game.DrawingOffset.X, Location.Y + DrawingOffset.Y + Game.DrawingOffset.Y);
            Console.ForegroundColor = TopObject.DisplayColor;
            
            Console.Write(TopObject.DisplayCharacter);
        }

        public bool IsPassableBy(Player character)
        {
            return character.ScalingAbility >= Architecture.ScalingDifficulty;
        }
        public void RemoveArchitecture()
        {
            _architecture = Level.BaseArchitecture;
        }
        public void RemoveObject(GameObject gObject)
        {
            _contents.Remove(gObject);
            ResetTopObject();
        }

        public void ResetTopObject()
        {
            var topObject = _contents.Count > 0
                                ? _contents.OrderByDescending(c => c.ZIndex).First()
                                : _architecture;

            if (TopObject != topObject)
            {
                TopObject = topObject;
                Level.ChangedBlocks.Add(this);
            }
        }
    }
}
